package com.muchfish.webflux.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;

@Configuration
public class WebFluxRouter {

    @Bean
    public RouterFunction<ServerResponse> routeExample(WebFluxHandler handler) {
        return route()
                .GET("/router/mono", handler::monoExample)
                .GET("/router/flux", handler::fluxExample)
                .build();
    }
}

@Component
class WebFluxHandler {

    public Mono<ServerResponse> monoExample(ServerRequest request) {
        return ok().contentType(MediaType.TEXT_PLAIN)
                .bodyValue("Hello, Mono from Router!");
    }

    public Mono<ServerResponse> fluxExample(ServerRequest request) {
        return ok().contentType(MediaType.APPLICATION_JSON)
                .body(Flux.just(1, 2, 3, 4, 5).collectList(), List.class);
    }

}

